package com.lebang.controller.sys.cences;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.lebang.common.Login;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.CencesNewHand;
import com.lebang.example.CencesNewHandExample;
import com.lebang.model.MyConfig;
import com.lebang.model.cences.CencesNewHandModel;
import com.lebang.service.cences.CencesNewHandService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;


/**
 * 新手任务统计
 *
 * @author xwj
 * @date 2020-02-10
 */
@Controller
@RequestMapping("/sys/cences/cencesnewhand")
public class CencesNewHandController {
    @Autowired
    private CencesNewHandService baseService;

    @Login
    @GetMapping("/list")
    public String list() {
        return "/cencesnewhand/list";
    }

    /**
     * @param page     页数
     * @param limit    条数
     * @param star     开始日期
     * @param end      结束日期
     * @param appStore 渠道
     * @param category 1新用户0老用户2全部
     * @return 返回数据
     */
    @PostMapping("/page")
    @ResponseBody
    @DataSource("commonDB")
    @Login
    public HashMap newlist(String likeBrand,Long page, Integer limit, Integer star, Integer end, String appStore, int category, int type) {
        HashMap map = new HashMap(1);
        CencesNewHandExample example = new CencesNewHandExample();
        CencesNewHandExample.Criteria c = example.createCriteria();
        example.setOffset((page - 1) * limit);
        example.setLimit(limit);
        example.setOrderByClause("time desc,id desc");
        c.andAppIdEqualTo(MyConfig.getEnv());
        if (star != null && end != null) {
            c.andTimeBetween(star, end);
        }
        if(!TextUtil.isEmpty(likeBrand)){
            c.andBrandLike(likeBrand+"%");
            appStore=null;
        }else {
            likeBrand=null;
            if (!TextUtil.isEmpty(appStore)) {
                c.andBrandEqualTo(appStore);
            }else {
                appStore=null;
            }
        }

        c.andTypeEqualTo(type);
        c.andCategoryEqualTo(category);
        map.put("count", this.baseService.countByExample(example));
        map.put("code", 0);

        List<CencesNewHand> masters = baseService.selectByExample(example);
        map.put("data", masters);
        return map;
    }

    @Login
    @RequestMapping("/export")
    @DataSource("commonDB")
    public String export(Integer star, Integer end, String appStore, int category, int type, HttpServletResponse response) throws IOException {
        CencesNewHandExample example = new CencesNewHandExample();
        CencesNewHandExample.Criteria c = example.createCriteria();
        example.setOrderByClause("time  desc,id desc");
        c.andAppIdEqualTo(MyConfig.getEnv());
        if (star != null && end != null) {
            c.andTimeBetween(star, end);
        }
        if (!TextUtil.isEmpty(appStore)) {
            c.andBrandEqualTo(appStore);
        }

        c.andTypeEqualTo(type);
        c.andCategoryEqualTo(category);
        List<CencesNewHand> masters = baseService.selectByExample(example);
        List<CencesNewHandModel> data = baseService.setExportData(masters);
        OutputStream outputStream = response.getOutputStream();

        //添加响应头信息
        response.setHeader("Content-disposition", "attachment; filename=" + "newhandtask.xlsx");
        //设置类型
        response.setContentType("application/msexcel;charset=UTF-8");
        //设置头
        response.setHeader("Pragma", "No-cache");
        //设置头
        response.setHeader("Cache-Control", "no-cache");
        //设置日期头
        response.setDateHeader("Expires", 0);
        WriteWorkbook writeWorkbook = new WriteWorkbook();
        writeWorkbook.setExcelType(ExcelTypeEnum.XLSX);
        writeWorkbook.setNeedHead(true);
        writeWorkbook.setOutputStream(outputStream);
        ExcelWriter writer = new ExcelWriter(writeWorkbook);
        WriteSheet writeSheet = new WriteSheet();
        writeSheet.setSheetNo(1);
        writeSheet.setRelativeHeadRowIndex(0);
        writeSheet.setClazz(CencesNewHandModel.class);
        writeSheet.setSheetName("sheet1");

        writer.write(data, writeSheet);
        writer.finish();
        outputStream.flush();

        return null;

    }


    @Login
    @PostMapping("/delete")
    @ResponseBody
    @DataSource("commonDB")
    public JsonData delete(Integer id) {
        baseService.deleteByTime(baseService.selectById(id).getTime());
        return Callback.success("success", "删除成功");
    }


    /**
     * 统计指定日期新手任务
     *
     * @param date 日期
     * @return 返回结果
     */
    @Login
    @PostMapping("/lastCheck")
    @ResponseBody
    public String cen(String date) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate end = LocalDate.parse(date, fmt);
        baseService.starDataInit(LocalDateTime.of(end.plusDays(1), LocalTime.MIN));
        return "success";
    }

    /**
     * 统计数据源
     */
    @PostMapping("/appstorepage")
    @ResponseBody
    @DataSource("commonDB")
    @Login
    public HashMap appStorePage(String likeBrand,Long page, Integer limit, Integer star, Integer end) {
        HashMap map = new HashMap(1);
        map.put("count",baseService.countData(likeBrand,star,end) );
        map.put("code", 0);
        map.put("data", baseService.sumData(likeBrand,(page - 1) * limit,limit,star,end));
        return map;
    }


    @Login
    @GetMapping("/appstorelist")
    public String appStoreList() {
        return "/cencesnewhand/appstorelist";
    }


}
